/**
 * 压缩图片
 * @param {Object} file { path: '', size: '' }
 * @param {Number} limitSize 压缩目标 MB
 */
export const imgCompress = {
	MB: 1024 * 1024,
	canvasId: 'imgCanvas',
	ctx: uni.createCanvasContext('imgCanvas'),
	// 获取可使用窗口宽度(提前使用uni.getSystemInfo获取windowWidth存在globalData)
	rpxToPx(number) {
		return number / 750 * getApp().globalData.systemInfo.windowWidth
	},
	// 获取文件信息
	getFileInfo(path) {
		return new Promise((resolve, reject) => {
			uni.getFileInfo({
				filePath: path,
				success: (res) => {
					console.log('File Size =>', `${res.size / this.MB}MB`)
					resolve(res.size)
				},
				fail: () => reject(null)
			})
		})
	},
	// 获取图片信息
	getImageInfo(path) {
		return new Promise((resolve, reject) => {
			uni.getImageInfo({
				src: path,
				success: (res) => resolve(res),
				fail: () => reject(null)
			})
		})
	},
	// 判断是否达到压缩目标
	getCompressImage(file, limitSize) {
		if (file.size > this.MB * limitSize) {
			return this.calcImaeg(file.path, limitSize);
		} else {
			return file.url
		}
	},
	// 递归
	async calcImaeg(url, limitSize) {
		const size = await this.getFileInfo(url)
		if (size > this.MB * limitSize) {
			const imageInfo = await this.getImageInfo(url)
			var maxSide = Math.max(imageInfo.width, imageInfo.height);
			var windowW = this.rpxToPx(750)
			var scale = 1
			if (maxSide > windowW) {
				scale = windowW / maxSide;
			}
			var imageW = Math.floor(imageInfo.width * scale)
			var imageH = Math.floor(imageInfo.height * scale)
			const newPath = await this.getCanvasImage(url, imageW, imageH)
			return this.calcImaeg(newPath, limitSize)
		} else {
			return url
		}
	},
	// 绘画
	getCanvasImage(imagePath, imageW, imageH) {
		return new Promise((resolve, reject) => {
			this.ctx.drawImage(imagePath, 0, 0, imageW, imageH)
			this.ctx.draw(false, () => {
				uni.canvasToTempFilePath({
					canvasId: this.canvasId,
					x: 0,
					y: 0,
					width: imageW,
					height: imageH,
					quality: 1,
					success: (res) => resolve(res.tempFilePath),
					fail: () => reject(imagePath)
				})
			})
		})
	}
}